package com.jx.gocomtask.webservice.restcontroller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.jx.gocomtask.webservice.DTO.*;
import com.jx.gocomtask.webservice.DTO.query.MessageQuery;
import com.jx.gocomtask.webservice.DTO.query.PageDTO;
import com.jx.gocomtask.webservice.DTO.query.Query;
import com.jx.gocomtask.webservice.entity.*;
import com.jx.gocomtask.webservice.repository.ExtTaskExtensionRepository;
import com.jx.gocomtask.webservice.repository.impl.StringEscapeUtils;
import com.jx.gocomtask.webservice.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.jx.gocomtask.webservice.repository.ExtTaskMessageRepository;
import com.jx.gocomtask.webservice.restcontroller.base.BaseRestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import phoenics.common.exception.ParamsException;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.List;

@Api(value = "与任务有关的API")
@RestController
@RequestMapping("/task")
public class TaskWebservice extends BaseRestController{
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TaskWebservice.class);

	@Autowired
	RestTemplate restTemplate;
	@Autowired
	SystemSuperApp systemSuperApp;
	@Autowired
	ExtTaskMessageRepository extTaskMessageRepository;
	@Resource
	ExtTaskSearchHistoryService extTaskSearchHistoryService;
	@Resource
	GroupService groupService;
	@Resource
	private ExtTaskMessageService extTaskMessageService;
	@Resource
	ExtTaskUserService extTaskUserService;
	@Resource
	ExtTaskExtensionRepository extTaskExtensionRepository;
	@Resource
	ExtTaskMessageReplyService extTaskMessageReplyService;
	@Autowired
	Route route;

	/**
	 *
	 * @param page
	 * @param size
	 * @param uuid  获取相关任务时使用
	 * @param groupid
	 * @return
	 */
	@ApiOperation(value = "任务查看", notes = "")
	@RequestMapping(value = "/tasksview", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public PageDTO<ExtTaskMessage> tasks_view(
			@RequestParam(value = "pg_index", defaultValue = "0") Integer page,
			@RequestParam(value = "pg_count", defaultValue = "10") Integer size,
			@RequestParam(value = "uuid", required = false) String uuid,
			@RequestParam(value = "groupid", required = false) String groupid){
		 Sort sort = new Sort(Direction.DESC, "id");
		 Pageable pageable = new PageRequest(page, size, sort);
		MessageQuery query = new MessageQuery();
		query.group = groupid;
		query.msgUUID = uuid;
		return extTaskMessageService.findAll(query, pageable);
	}


	/**
	 * 任务关联
	 * @param super_uuid  父uuid
	 * @param child_uuid  子uuid
	 * @param type		0取消  1关联
	 * @return
	 */
	@ApiOperation(value = "任务关联/取消关联", notes = "")
	@RequestMapping(value = "/tasks/relation", method = RequestMethod.PUT)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public void tasks_view(
			@RequestParam(value = "super_uuid", required = true) String super_uuid,
			@RequestParam(value = "child_uuid", required = true) String child_uuid,
			@RequestParam(value = "type", required = true) Integer type){

		extTaskMessageService.relevance(super_uuid, child_uuid, type);
	}

	/**
	 * 获取列表
	 * @param request
	 * @param wptoken
	 * @param type	@wo wo@
	 * @param list_type  列表方式（一览界面使用）	create:按创建时间  deadline：按结束时间
	 * @param action_type 操作方式	up:上拉刷新  down：下拉刷新
	 * @param deadline	即将到期(最小单位日)
	 * @param status
	 * @param uuid  msg_uuid
	 * @param search_type  0:普通查询使用 1:任务关联列表使用
	 * @param page
	 * @param size
	 * @return
	 */
	@ApiOperation(value = "任务列表查看(一览)", notes = "")
	@RequestMapping(value = "/tasks", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public PageDTO<ExtTaskMessage> findAll(
			HttpServletRequest request,
			@RequestParam(value="token",  required=true) String wptoken,
			@RequestParam(value = "type", required = false) String type,
			@RequestParam(value = "list_type", defaultValue = "create") String list_type,
			@RequestParam(value = "action_type", defaultValue = "down") String action_type,
			@RequestParam(value = "begin_deadline", required = false) Long deadline,
			@RequestParam(value = "end_deadline", required = false) Long end_deadline,
			@RequestParam(value = "userName", required = false) String userName,
			@RequestParam(value = "key_word", required = false) String key_word,
			@RequestParam(value = "uuid", required = false) String uuid,
			@RequestParam(value = "status", required = false) List<TaskStatus> status,
			@RequestParam(value = "search_type", defaultValue = "0") Integer search_type,
			@RequestParam(value = "pg_index", defaultValue = "0") Integer page,
			@RequestParam(value = "pg_count", defaultValue = "10") Integer size){
		String userid=(String)request.getAttribute("userid");
		MessageQuery messageQuery = new MessageQuery();
		messageQuery.type = StringEscapeUtils.escapeSql(type);
		messageQuery.list_type = StringEscapeUtils.escapeSql(list_type);
		messageQuery.action_type = StringEscapeUtils.escapeSql(action_type);
		messageQuery.userId = userid;
		if(StringUtils.isNotEmpty(userName)) {
			try {
				userName = URLDecoder.decode(userName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			messageQuery.userName = StringEscapeUtils.escapeSql(userName);
		}
		if(StringUtils.isNotEmpty(key_word)) {
			try {
				key_word = StringEscapeUtils.escapeSql(key_word);
				key_word = URLDecoder.decode(key_word, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			messageQuery.keyword = key_word;
		}
		if(null != status && status.size() > 0) {
			String str = "";
			for(TaskStatus taskStatus : status){
				str += taskStatus.ordinal() + ",";
			}
			messageQuery.statusList = str.substring(0, str.lastIndexOf(","));
		}
		if(null != deadline && null != end_deadline && end_deadline > deadline) {
			messageQuery.begin_deadline = deadline;
			messageQuery.end_deadline = end_deadline;
		}

		messageQuery.search_type = search_type;
		messageQuery.msgUUID = StringEscapeUtils.escapeSql(uuid);
		messageQuery.page = page;
		messageQuery.size = size;
		return extTaskMessageService.findAll(messageQuery);
	}



	/**
	 * 任务列表查看统计
	 * @param request
	 * @param wptoken
	 * @param type	@wo wo@
	 * @param status
	 * @return
	 */
	@ApiOperation(value = "任务列表查看统计(看板)", notes = "")
	@RequestMapping(value = "/tasks/total", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public ViewTotalDTO findAllCount(
			HttpServletRequest request,
			@RequestParam(value="token",  required=true) String wptoken,
			@RequestParam(value = "type", required = false) String type,
			@RequestParam(value = "status", required = false) List<TaskStatus> status){
		String userid=(String)request.getAttribute("userid");
		MessageQuery messageQuery = new MessageQuery();
		messageQuery.type = StringEscapeUtils.escapeSql(type);
		messageQuery.userId = userid;
		if(null != status && status.size() > 0) {
			String str = "";
			for(TaskStatus taskStatus : status){
				str += taskStatus.ordinal() + ",";
			}
			messageQuery.statusList = str.substring(0, str.lastIndexOf(","));
		}
		ViewTotalDTO dto = extTaskMessageService.count(messageQuery);
		return dto;
	}

	@ApiOperation(value = "即信看板（任务分配）")
	@RequestMapping(value = "/tasks/look", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	public PageDTO<TotalLookDTO> findLookAll(
			HttpServletRequest request,
			@RequestParam(value="token",  required=true) String wptoken,
			@RequestParam(value = "status", required = false) List<TaskStatus> status,
			@RequestParam(value = "pg_index", defaultValue = "0") Integer page,
			@RequestParam(value = "pg_count", defaultValue = "5") Integer size
	){
		MessageQuery query = new MessageQuery();
		query.userId=(String)request.getAttribute("userid");
		query.page = page;
		query.size = size;
		PageDTO<TotalLookDTO> pageDTO = extTaskMessageService.findLookAll(query);

		return pageDTO;
	}

	@ApiOperation(value = "任务查看", notes = "三种状态：normal author executor")
	@RequestMapping(value = "/tasks/view/{id}", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public ExtTaskMessage findOneTask(
			@PathVariable("id") String taskid,
			@RequestParam(value="token",  required=true) String wptoken,HttpServletRequest request){
		String userid=(String)request.getAttribute("userid");
		ExtTaskMessage extTaskMessage_base= extTaskMessageService.findByUUID(taskid, userid);
		extTaskMessage_base.setUserId(userid);
		return extTaskMessage_base;
	}

	/**
	 * 创建者编辑
	 * @param taskid
	 * @param wptoken
	 * @param taskBody
	 * @param request
	 */
	@ApiOperation(value = "创建者编辑任务", notes = "")
	@RequestMapping(value = "/tasks/edit/{id}", method = RequestMethod.PUT)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public ExtTaskMessage taskstatus_edit(
			@PathVariable("id") String taskid,
			@RequestParam(value="token",  required=true) String wptoken,
			@RequestBody  TaskBody taskBody,HttpServletRequest request){
		if(null == taskBody)
			throw new ParamsException();
		String userid=(String)request.getAttribute("userid");
		ExtTaskMessage extTaskMessage = extTaskMessageService.updateByUUID(taskid, userid, taskBody);
		return extTaskMessage;
	}


	@ApiOperation(value = "执行者编辑任务状态", notes = "")
	@RequestMapping(value = "/tasks/user/{id}", method = RequestMethod.PUT)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public ExtTaskMessage taskstatus_editUser(
			@PathVariable("id") String taskid,
			@RequestParam(value="token",  required=true) String wptoken,
			@RequestBody  TaskBody taskBody,HttpServletRequest request){
		if(null == taskBody)
			throw new ParamsException();
		String userid=(String)request.getAttribute("userid");
		extTaskUserService.updateByUUIDAndTaskUser(taskid, userid, taskBody);

		ExtTaskMessage extTaskMessage = extTaskMessageService.findByUUID(taskid, userid);

		//            调用存储过程状态统计
		extTaskExtensionRepository.updateNumber(extTaskMessage.getId());
		return extTaskMessage;
	}


	@ApiOperation(value = "获取执行者任务列表", notes = "")
	@RequestMapping(value = "/tasks/user/{id}", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public Page<ExtTaskUser> taskstatus_findUser(
			@RequestParam(value = "pg_index", defaultValue = "0") Integer page,
			@RequestParam(value = "pg_count", defaultValue = "10") Integer size,
			@PathVariable("id") String taskid,
			@RequestParam(value="token",  required=true) String wptoken,HttpServletRequest request){
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable pageable = new PageRequest(page, size, sort);

		Query query = new Query();
		query.TaskUUId = taskid;
		query.user = (String)request.getAttribute("userid");
		Page<ExtTaskUser> extTaskUserPage = extTaskUserService.findByList(query, pageable);
		return extTaskUserPage;
	}


	@ApiOperation(value = "获取搜索历史列表", notes = "")
	@RequestMapping(value = "/tasks/search", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public List<ExtTaskSearchHistory> taskfindUserHistory(
			@RequestParam(value="token",  required=true) String wptoken,HttpServletRequest request){
		String userid=(String)request.getAttribute("userid");
		List<ExtTaskSearchHistory> extTaskUserPage =
				extTaskSearchHistoryService.findList(userid);
		return extTaskUserPage;
	}

	/**
	 * 添加回复列表
	 * @param request
	 * @param wptoken
	 * @return
	 */
	@ApiOperation(value = "添加回复")
	@RequestMapping(value = "/tasks/reply", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public ExtTaskMessageReply addReqly(
			HttpServletRequest request,
			@RequestParam(value="token",  required=true) String wptoken,
			@RequestParam(value = "msg_id", required = true) String msg_id,
			@RequestBody MsgContentDTO body){
		if(null == body || StringUtils.isEmpty(body.content) || StringUtils.isEmpty(body.type))
			throw new ParamsException();

		String userid=(String)request.getAttribute("userid");
		ExtTaskMessageReply reply = new ExtTaskMessageReply();
		reply.setContent(body.content);
		Long time = System.currentTimeMillis();
		reply.setCreateTime(new Timestamp(time));

		if("gocom".equals(body.type)) {
			reply.setTaskUser(userid);
			reply.setTaskUserName(route.takeUserInfo(userid));
		}else{
//			reply.setTaskWechatUser(userid);
//			reply.setTaskWechatUserName(route.takeUserInfo(userid));
		}

		reply = extTaskMessageReplyService.addReply(msg_id, userid, reply);
		return reply;
	}

	/**
	 * 获取回复列表
	 * @param request
	 * @param wptoken
	 * @param page
	 * @param size
	 * @return
	 */
	@ApiOperation(value = "获取回复列表")
	@RequestMapping(value = "/tasks/reply", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public Page<ExtTaskMessageReply> findReplyAll(
			HttpServletRequest request,
			@RequestParam(value="token",  required=true) String wptoken,
			@RequestParam(value = "msg_id", required = true) String msg_id,
			@RequestParam(value = "pg_index", defaultValue = "0") Integer page,
			@RequestParam(value = "pg_count", defaultValue = "10") Integer size){
		String userid=(String)request.getAttribute("userid");
		MessageQuery messageQuery = new MessageQuery();
		messageQuery.msgUUID = msg_id;

		messageQuery.page = page;
		messageQuery.size = size;
		return extTaskMessageReplyService.findAll(messageQuery);
	}


	/**
	 * 获取上下文列表
	 * @param request
	 * @param wptoken
	 * @param page
	 * @param size
	 * @return
	 */
	@ApiOperation(value = "获取上下文列表")
	@RequestMapping(value = "/tasks/context", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@CrossOrigin(origins = "*")
	public Page<ExtTaskMessageHistory> findContextAll(
			HttpServletRequest request,
			@RequestParam(value="token",  required=true) String wptoken,
			@RequestParam(value = "msg_id", required = true) String msg_id,
			@RequestParam(value = "pg_index", defaultValue = "0") Integer page,
			@RequestParam(value = "pg_count", defaultValue = "10") Integer size){
		String userid=(String)request.getAttribute("userid");
		MessageQuery messageQuery = new MessageQuery();
		messageQuery.msgUUID = msg_id;

		messageQuery.page = page;
		messageQuery.size = size;
		return extTaskMessageService.findContentAll(messageQuery);
	}

	// todo 上下文测试
	@RequestMapping(value = "/tasks/ssss", method = RequestMethod.GET)
	public void addContext(
			@RequestParam(value="token",  required=true) String wptoken,
			@RequestParam(value = "content", required = true) String content,
			@RequestParam(value = "group", required = true) String group
	){
		MessageQuery query = new MessageQuery();
		query.source = 0;
		query.group = group;
		extTaskMessageService.addContent(query, content, query.source);
	}

}
